package com.yzc.service.Impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yzc.apis.logClient.MainOrderLogClient;
import com.yzc.constants.MqConstants;
import com.yzc.execption.ZcException;
import com.yzc.mapper.TicketMainOrderMapper;
import com.yzc.model.entity.ticket_order.OrderMain;
import com.yzc.model.entity.log.OrderStatusLog;
import com.yzc.rabbit.OrderStatus;
import com.yzc.redis.RedisUtil;
import com.yzc.result.Result;
import com.yzc.result.ResultCodeEnum;
import com.yzc.service.PaymentService;
import com.yzc.util.RabbitMQUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

import static com.yzc.constant.RedisConstant.CACHE_EXPIRE_TIME;
import static com.yzc.constant.RedisConstant.ORDER_RECORD_MAIN;

@Slf4j
@Service
@RequiredArgsConstructor
public class PaymentServiceImpl implements PaymentService {

    private final TicketMainOrderMapper orderMainMapper;
    private final RabbitMQUtil rabbitMQUtil;
    private final RedisUtil redisUtil;
    private final MainOrderLogClient mainOrderLogClient;


    private String getUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            return authentication.getName();
        }
        return "system"; // 默认值，根据业务需求调整
    }

    @Override
    @Transactional
    public Result<String> payOrder(Long orderId, String paymentMethod) {
        // 参数校验
        if (orderId == null || orderId <= 0) {
            throw new ZcException(ResultCodeEnum.FAIL.getCode(),"订单ID无效");
        }
        if (paymentMethod == null || paymentMethod.isEmpty()) {
            throw new ZcException(ResultCodeEnum.FAIL.getCode(),"支付方式不能为空");
        }

        String cacheKey = ORDER_RECORD_MAIN + orderId;
        OrderMain order = (OrderMain) redisUtil.get(cacheKey);
        if (order == null) {
            // 查询订单
            order = orderMainMapper.selectOne(
                    new LambdaQueryWrapper<OrderMain>()
                            .eq(OrderMain::getOrderId, orderId)
            );
            if (order == null) {
                throw new ZcException(ResultCodeEnum.FAIL.getCode(), "订单不存在");
            }
            redisUtil.set(cacheKey, order, CACHE_EXPIRE_TIME);
        }


        // 检查订单状态是否为待支付
        if (OrderStatus.status_UNPAID.getCode() != order.getOrderStatus()) {
            log.error("订单状态已更新，无需支付，订单状态: {}", order.getOrderStatus());
            throw new ZcException(ResultCodeEnum.FAIL.getCode(),"订单当前状态不可支付");
        }

        // 模拟调用支付接口
        boolean paymentSuccess = mockPaymentGateway(paymentMethod, order.getTotalAmount());


        // 处理支付结果
        if (paymentSuccess) {
            rabbitMQUtil.cancelDelayedMessage(MqConstants.DELAY_EXCHANGE_NAME, "order.unpaid", orderId);
            // 更新订单状态和支付时间
            UpdateWrapper<OrderMain> updateWrapper = new UpdateWrapper<>();
            updateWrapper
                    .eq("order_id", orderId)
                    .set("order_status", OrderStatus.status_PAID.getCode())
                    .set("payment_time", new Date());

            int rows = orderMainMapper.update(updateWrapper);
            if (rows <= 0) {
                throw new ZcException(ResultCodeEnum.FAIL.getCode(), "订单状态更新失败");
            }

            order.setOrderStatus(OrderStatus.status_PAID.getCode());
            order.setPaymentTime(new Date());
            redisUtil.set(cacheKey, order, CACHE_EXPIRE_TIME);

            logPaymentResult(orderId, order, true, "支付成功，支付方式: " + paymentMethod);
            return Result.success("支付成功");
        } else {
            logPaymentResult(orderId, order, false, "支付失败，支付方式: " + paymentMethod);
            throw new ZcException(ResultCodeEnum.FAIL.getCode(), "支付失败，支付方式: " + paymentMethod);
        }
    }

    /**
     * 模拟支付接口
     * @param paymentMethod 支付方式
     * @param amount        支付金额
     * @return 支付结果
     */
    private boolean mockPaymentGateway(String paymentMethod, BigDecimal amount) {
        return true;
    }

    private void logPaymentResult(Long orderId,OrderMain order, boolean success, String remark) {
        OrderStatusLog orderLog = new OrderStatusLog();
        orderLog.setOrderId(orderId);
        orderLog.setStatus(success ? OrderStatus.status_PAID.getCode() : OrderStatus.status_UNPAID.getCode());
        orderLog.setOperator(getUsername() + ":" + order.getUserId());
        orderLog.setRemark(remark);
        orderLog.setCreateTime(new Date());

        // 保存日志
        mainOrderLogClient.createOrderLog(orderLog);

        if (success) {
            log.info("订单支付成功，订单ID: {}", orderId);
        } else {
            log.error("订单支付失败，订单ID: {}", orderId);
        }
    }
}